<?php
/**
 * Created by cmb_weixin.master.
 * File: QuestionResult.php
 * User: xuewl
 * Date: 2017/12/18
 * Time: 01:21
 */

namespace app\product\service;
use app\common\library\Service;

class QuestionResult extends Service
{

    use \app\common\library\traits\Model;
    protected $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('product/question_result');
    }


    /**
     * 创建初核答案
     * @param $user     array     产品ID
     * @param $product  array     用户ID
     * @param $question array       问答合集
     * @return mixed
     */
    public function create($user = [], $product = [], $question = []) {
        $info = [
            'product_id' => $product['id'],
            'user_id'   => $user['id']
        ];
        $rules = $product->question_template_info->rules;
        $props = $product->question_template_info->content_prop;

        if(count($props) != count($question)) {
            $this->error = '请回答所有的初核问卷';
            return false;
        }

        $info['result'] = 1;
        $info['content'] = [];
        foreach ($props AS $pid => $prop) {
            $key = $pid.'.'.$question[$pid];
            $value = \fast\ArrayHelper::map($prop['value'], 'id', 'prop_value');
            $info['content'][$prop['name']] = $value[$question[$pid]];
            if(!$key || !isset($rules[$key])) {
                $this->error = "初核问卷答案不合法，请重新提交";
                return false;
                break;
            }
            if($rules[$key] != 1) {
                $info['result'] = 0;
                break;
            }
        }
        $result = $this->save($info,[],'add');
        if(!$result) {
            $this->error = $this->getError();
            return false;
        }

        return $result;
    }


    /**
     * 校验初核答案
     * @param array $rules
     * @param array $props
     * @param array $question
     * @return bool
     */
    public function valid($rules = [], $props = [], $question = []) {
        return false;
    }

}